const lodash = require('lodash')
const loginFns = require("../common/login")
import { pageFns } from '../utils/pageHelper'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleDao } from '@/dao/articleDao'

const SELECTORS = { "JUMPTO": ["div[role=\"tablist\"] > div > div:nth-child(2) > a:nth-child(3)"], "INPUTBOX": ["span::-p-text(\"Photo/video\")", "div[role=\"button\"]:nth-child(2) > div:nth-child(1) > span"], "TYPINGBOX": ["div[role=\"presentation\"] > div:nth-child(1) span"], "ADDINGBOX": ["div[aria-label=\"Photo/video\"]"], "UPLOADBOX": ["div[id=\"toolbarLabel\"] + div > div:nth-child(1) > input", "div[role=\"presentation\"] + div > div > div > div> div > input"], "COMFIRMBTNS": ["div[role=\"dialog\"] span::-p-text(\"Post\")", "div[aria-label=\"Post\"]", "form[method=\"POST\"] div[aria-label=\"Post\"]"], "DIALOGBOX": ["div[role=\"dialog\"]"] }
// 发布
async function startPost(page, content, files, selectors) {
    /**
     * @description JUMP TO DISCUSS TAB
    */
    let res = await pageFns.deepRetry(selectors.JUMPTO, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector, { delay: 100 })
    }, { page: page })
    if (res.err) {
        return res
    }
    /**
     * @description BOX INPUT STATUS METHOD
    */
    res = await pageFns.deepRetry(selectors.INPUTBOX, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
    }, { page: page, timeout: 20000 })
    if (res.err) {
        return res
    }
    /**
    * @description TYPING INPUT STATUS METHOD
    */
    res = await pageFns.deepRetry(selectors.TYPINGBOX, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await pageFns.delay(4000)
        await page.type(selector, content)
    }, { page: page, timeout: 10000 })
    if (res.err) {
        return res
    }
    /**
    * @description CLICK ADD PHOTO BOX
    */
    if (!lodash.isEmpty(selectors.ADDINGBOX)) {
        let res = await pageFns.deepRetry(selectors.ADDINGBOX, page, async (selector, page) => {
            await page.waitForSelector(selector)
            await page.click(selector)
        }, { page: page })
        if (res.err) {
            return res
        }
        await pageFns.delay(2 * 1000)
    }

    /**
    * @description UPLOAD IMAGE STATUS METHOD
    */
    res = await pageFns.deepRetry(selectors.UPLOADBOX, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await pageFns.fileUpload({
            page,
            element: selector,
            files: files,
        })
    }, { page: page, timeout: 1000, wait: 1000 })

    if (res.err) {
        return res
    }
    /**
     * @description PUBLISH STATUS METHOD
     */
    res = await pageFns.deepRetry(selectors.COMFIRMBTNS, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
        await pageFns.delay(4000)
        await page.waitForFunction((selector) => {
            return !document.querySelector(selector);
        }, {}, selectors.DIALOGBOX);
    }, { page: page, timeout: 10 * 1000, wait: 10 * 1000 })

    if (res.err) {
        return res
    }

    return { data: "发布成功" }
}

const LOGINS = {
    LOGINBTNS: [],
    USERNAMES: ['input[name="email"]'],
    NEXTSTEPS: [],
    PASSWORDS: ['input[name="pass"]'],
    COMFIRMBTNS: ['button[name="login"]'],
    UNLOGINFLAGS: ['button[name="login"]']
}

async function goPost(page, task, article, rule) {
    let selectors = JSON.parse(rule.codeRule)
    if (lodash.isEmpty(selectors)) {
        return { err: "找不到发布规则:" + task.id }
    }
    let res = await loginFns.checkLogin(page, task, LOGINS)
    if (res.err) {
        console.log("goPost.checkLogin", res)
        return res
    }
    // 收集图片
    try {
        let dataFields = JSON.parse(task.dataFields)
        if (lodash.isEmpty(dataFields)) {
            return { err: "没有指定的数据" }
        }
        let aiResult = JSON.parse(article.aiResult)
        let contents = []
        for (let dataField of dataFields) {
            contents.push(aiResult[task.lang][dataField])
        }
        console.log(dataFields, article, task.lang)
        let images = funcFns.getImages(ArticleDao.folderPath(article))
        return await startPost(page, contents.join("."), images, selectors)
    } catch (err) {
        console.log("goPost", err)
        return { err: err }
    }
}

export { goPost }